package com.manong.web.intercptor;

import com.alibaba.fastjson.JSON;
import com.manong.constant.RedisConstant;
import com.manong.domain.Employee;
import com.manong.util.JsonResult;
import com.manong.util.RedisUtils;
import com.manong.util.RequiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.ArrayList;

@Component
public class CheckPermissionIntercptor implements HandlerInterceptor {
    @Autowired
    private RedisUtils redisUtils;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果是 OPTIONS 请求，直接放行
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        response.setContentType("application/json;charset=utf-8");
        // 获取userId
        String userId = request.getHeader("userId");
        // redis中获取用户信息
        String objJson = redisUtils.get(RedisConstant.LOGIN_USER_INFO + userId);
        Employee employee = JSON.parseObject(objJson, Employee.class);
        // 判断是否为超管
        if(employee.getAdmin()){
            return true;
        }
        // 获取当前方位的方法
        // 拦截器的参数类型只有两种
        // 当你访问的控制器的方法的时候类型就是变声HandlerMethod
        // 当你访问静态资源的时候非HandlerMethod
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            // 获取方法上的注解
            RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
            // 判断注解是否为空，如果为空表示不需要权限可以访问
            if(annotation == null){
                return true;
            }
            // 上redis中获取用户拥有的权限表达式和集合
            String expressionsJson = redisUtils.get(RedisConstant.LOGIN_INFO_EXPRESSIONS + userId);
            ArrayList<String> expressions = JSON.parseObject(expressionsJson, ArrayList.class);
            // 判断注解中的权限表达式的集合是否在redis中，如果在就放行
            String expression = annotation.expression();
            if(expressions.contains(expression)){
                return true;
            }
            // 如果不在集合中返回403
            JsonResult result = new JsonResult(403, "暂无权限", "fail", null);
            response.getWriter().write(JSON.toJSONString(result));
            return false;
        }
        return true;
    }
}
